import 'package:flutter/material.dart';

//class JoyHistoryBrowsePage extends StatefulWidget{

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:joyagoo/pages/widget/joyHomeEmptyWidget.dart';
import 'package:joyagoo/pages/widget/joy_product_card_widget.dart';

import '../config/app_colors.dart';
import '../model/productListModel.dart';
import '../utils/JoyBlocUtil.dart';
import 'joy_home_bloc.dart';


class JoyHistoryBrowsePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return JoyHistoryBrowsePageState();
  }

}
class JoyHistoryBrowsePageState extends State<JoyHistoryBrowsePage>{

  late JoyHomeBloc _historyBloc;
  late EasyRefreshController _refreshController;
  List _browseProducts = [];
  String _errorMessage = "no_search_results".tr;
  bool isShowButton = false;
  bool isNetError = false;
  bool isLoading = true;
  int pageSize = 20;
  int pageNumber = 1;


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.transparent,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                AppColors.backHomeYellowGround,
                AppColors.backHomeYellowGround,
              ],
            ),
          ),
        ),
        title: Text(
          "Browse History".tr,
          style: TextStyle(
            color: AppColors.primary,
            fontSize: 20.sp,
            fontWeight: FontWeight.bold,
            letterSpacing: 0.5,
          ),
        ),
        leading: GestureDetector(
          onTap: () => Navigator.pop(context),
          child: Container(
            margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: AppColors.primaryVariant,
              size: 18.sp,
            ),
          ),
        ),
      ),
      body: blocMian(),
    );
  }

  @override
  void initState() {
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  Widget blocMian(){
    return JoyBlocUtil.getAppNoBarBloc(
        backgroundColor: AppColors.background,
        builder: (context, state) {
          return _buildBody();
        }, create: (_) {
      _historyBloc = JoyHomeBloc();
      _historyBloc.add(GetHistoryProductViewEvent(context,pageNumber,pageSize));
      return _historyBloc;
    }, buildWhen: (previousState, state) {



      if(state is GetHistoryProductViewEventSuccess){

        isNetError = false;
        isShowButton = true;
        isLoading = false;

        ProductListModel modelList = state.data;

        if(pageNumber == 1){
          _browseProducts.clear();
          _browseProducts.addAll(modelList.productModels);
        }else{
          _browseProducts.addAll(modelList.productModels);
        }
        _refreshController.resetHeader();
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetFooter();
        if(modelList.productModels.length < pageSize){
          _refreshController.finishLoad(IndicatorResult.noMore);
        }else{
          _refreshController.finishLoad();
        }

        if(_browseProducts.isEmpty){
          _errorMessage = "no_results_found".tr;
        }

        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();

        return true;

      }
      if(state is GetHistoryProductViewEventFailure){

        isNetError = true;
        isShowButton = true;
        isLoading = false;
        _errorMessage = state.errMsg??"network_error".tr;
        pageNumber = pageNumber - 1;
        if(pageNumber <= 0){
          pageNumber = 1;
        }


        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();
        return true;

      }
      return false;
    });
  }


  void loadData (){

    pageNumber =1;
    isLoading = true;
    _historyBloc.add(GetHistoryProductViewEvent(context,pageNumber,pageSize));

  }

  void loadMoreData (){

    pageNumber = pageNumber + 1;
    _historyBloc.add(GetHistoryProductViewEvent(context,pageNumber,pageSize));

  }


  Widget _buildBody() {
    // 如果正在加载且没有数据，显示骨架屏
    if (isLoading && _browseProducts.isEmpty) {
     // return PmHistoryBrowseSkeletonWidget();
    }

    return EasyRefresh(
        // 🔥 设置下拉刷新样式 - 文字颜色为黑色
        header: ClassicHeader(
          dragText: 'Pull to refresh',
          armedText: 'Release to refresh', 
          readyText: 'Refreshing...',
          processingText: 'Refreshing...',
          processedText: 'Refresh completed',
          noMoreText: 'No more data',
          failedText: 'Refresh failed',
          messageText: 'Last updated at %T',
          iconTheme: const IconThemeData(
            color: Colors.black, // 核心：设置图标颜色
            size: 24, // 可选：设置图标大小
          ),
          textStyle: TextStyle(color: Colors.black, fontSize: 14.sp),
          messageStyle: TextStyle(color: Colors.black, fontSize: 10.sp),
        ),
        // 🔥 设置上拉加载样式 - 文字颜色为黑色
        footer: ClassicFooter(
          dragText: 'Pull to load',
          armedText: 'Release to load',
          readyText: 'Loading...',
          processingText: 'Loading...',
          processedText: 'Loading completed',
          noMoreText: 'No more data',
          failedText: 'Loading failed',
          messageText: 'Last updated at %T',
          iconTheme: const IconThemeData(
            color: Colors.black, // 核心：设置图标颜色
            size: 24, // 可选：设置图标大小
          ),
          textStyle: TextStyle(color: Colors.black, fontSize: 14.sp),
          messageStyle: TextStyle(color: Colors.black, fontSize: 10.sp),
        ),
        controller: _refreshController,
        onRefresh: () async {
          loadData ();
        },
        onLoad: (){
          loadMoreData();
        },
        child: _buildMain()
    );
  }

  Widget _buildMain(){

    if (_browseProducts.isEmpty && isNetError == true) {
      return JoyHomeEmptyWidget(
        messageError: _errorMessage,
        isNetError: isNetError,
        errorImagePath: "",
        tapOnCallBack: () {
          loadData ();
        },
      );
    }

    return SingleChildScrollView(
      child: Column(
        children: [
          // 商品网格
          GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 12.h,
              childAspectRatio: 0.72,
            ),
            itemCount: _browseProducts.length,
            itemBuilder: (context, index) {
              return  JoyProductCardWidget(
                productModel: _browseProducts[index],
                onTap: () {
                  // 添加点击动画效果
                },
              );

            },
          ),
        ],
      ),
    );
  }

}